<template>
  <div class="g-container">
    <div id="dBanner"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.3, 1000)
camera.position.set(5, 10, 20)
camera.lookAt(0, 0, 0)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

// 初始化坐标系
// const axesHelper = new THREE.AxesHelper(200)
// // 添加坐标系
// scene.add(axesHelper)

// 初始化控制器
const controls = new OrbitControls(camera, renderer.domElement)
controls.minPolarAngle = 0
controls.maxPolarAngle = Math.PI * 0.48
// 绑定控制器（更新渲染器）
controls.addEventListener('change', () => {
  renderer.render(scene, camera)
})

const loader = new GLTFLoader()
let space = null

loader.load('/src/model/space_boi.glb', model => {
  const root = model.scene.getObjectByName('RootNode')
  const rootChild = {}
  root.children.forEach(item => {
    rootChild[item.name] = item
  })
  space = { ...rootChild, root: model.scene }

  console.log(
    root.children.map(item => {
      return item.name
    })
  )
  console.log(space.body)
  resetPositionCenter(space.waves2)

  scene.add(model.scene)
})

const resetPositionCenter = model => {
  const { x, y, z } = model.position
  const scale = model.scale
  model.children[0].position.set(x / scale.x, y / scale.y, z / scale.z)
  model.position.set(0, 0, 0)
}

onMounted(() => {
  document.querySelector('#dBanner').appendChild(renderer.domElement)
  animate()
})

const animate = () => {
  requestAnimationFrame(animate)
  if (space) {
    space.root.rotation.y += 0.002
    space.body.rotation.z -= 0.002
    space.waves2.rotation.z -= 0.002
    space.Sphere.rotation.z += 0.01
    space.Sphere004.rotation.z += 0.01
    space.Sphere003.rotation.z += 0.01
    space.Sphere005.rotation.z += 0.01
    space.Sphere008.rotation.z += 0.01
  }
  renderer.render(scene, camera)
}
</script>

<style scoped>
.g-container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>
